
/*
 * fx
 *
 * Created on Oct 13, 2009, 6:13:20 PM
 */
package AlertSystem;
import GraphsWindowPackage.GraphsWindow;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.paint.Color;
import javafx.scene.layout.VBox;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.LayoutInfo;
import javafx.scene.shape.Rectangle;
import java.lang.System;
import javafx.scene.Group;
import javafx.stage.Alert;
import java.sql.SQLException;
import javafx.scene.text.TextAlignment;

/**
 * @author quang
 */

def screenWidth: Number = bind Window.screenWidth;
def screenHeight: Number = bind Window.screenHeight;
def windowContentYOffset: Number = bind Window.windowContentYOffset;

def finishedMessage = "Congratulations ! You have finished your task.";
def connection = Window.connection;
def font2 = Window.font2;
def headerRectHeight = bind Window.windowContentYOffset;
//def tabHeight = bind if (screenWidth < screenScale * 1280) 23 else 26;
def tabHeight = 22;
def tabsYOffset = bind (headerRectHeight - tabHeight) + 2;

def tabNames: String[] = ['Labs', 'Med. Orders', 'OP Notes', 'Progress Notes',
'EKG', 'Microlabs', 'Radiology', 'HP Summaries', 'Procedures' ];

def dataTableNameSeq: String[] = ['{inDBName}.lab', '{inDBName}.medication', '{inDBName}.op_notes', '{inDBName}.progressnote',
'{inDBName}.ekgreport', '{inDBName}.microreport', '{inDBName}.radiologyreport', '{inDBName}.handp', '{inDBName}.procedures'];

def dateTimeFieldNameSeq = [ 'dateTime', 'finishDateTime', 'dateTime', 'dateTime',
'dateTime', 'dateTime', 'dateTime', 'dateTime', 'finishDateTime'];

def textFieldName = 'text';

def hasTextWindowSeq: Boolean[] = [false, false, true, true,
true, true, true, true, true];

def tabSpacing = 13;

def tabWidth = bind (screenWidth / (sizeof dataTableNameSeq + 1)) + tabSpacing - 1;

public class Controller extends Window {

    public var userName: String;
    public var resolution: String;

    var patientId: String;

    var patientIdList: String[] = []; //list of patient ids that has not been given data in survey

    var contents: Node[];// = bind [ graphsWindow, textWindowContents ] ;

    function createGraphsWindow(patientId: String): Window {
            return GraphsWindow {
                userName: userName
                patientId: patientId
            }
    }   

    function createTextModeWindow(patientId: String, dataTableName: String,
    dateTimeFieldName: String, textFieldName: String, hasTextWindow: Boolean): Node {
        var window: Node;
        if (dataTableName == '{inDBName}.lab') {
            def infoTitle = Text {
                content: " Lab Time                            Lab Name | Value | Normal Range"
                font: Font {
                    name: "Arial Bold"
                    size: 12
                }
                fill: Color.BLUE
            }
            def listContentWindow = ListContentWindow {
                    dataTableName: '{inDBName}.lab'
                    patientId: patientId
                    dateTimeFieldName: 'dateTime'
                    textFieldName: 'text'
                    hasTextWindow: false
                    windowHeight: screenHeight - windowContentYOffset - 15
                }
            window = VBox {
                translateY: Window.windowContentYOffset
                content: [infoTitle, listContentWindow]
            }
        }
        else
        window = ListContentWindow {
            dataTableName: dataTableName
            patientId: patientId
            dateTimeFieldName: dateTimeFieldName
            textFieldName: textFieldName
            hasTextWindow: hasTextWindow
        }
        return window;
    }

    function createTextModeTab(text: String, window: Node, tabIdx: Integer): Button {
        return Button {
            text: text
//            textAlignment: TextAlignment.LEFT
//            font: if (screenWidth < screenScale * 1280) tabFont1 else tabFont2
            font: tabFont2
            layoutInfo: LayoutInfo {
                width: tabWidth
            }
            action: function () {
                    setVisibility(tabIdx);                
            }
        }
    }

    function createTextModeTabs(){
        for (i in [0..sizeof dataTableNameSeq - 1]){
            createTextModeTab(tabNames[i], contents[i+1], i+1)
        }
    }

    function createTextWindowContents(patientId: String): Node[] {
        [
            //createGraphsWindow(patientId),
            for (i in [0..sizeof dataTableNameSeq - 1]){
                createTextModeWindow(patientId, dataTableNameSeq[i], dateTimeFieldNameSeq[i], textFieldName, hasTextWindowSeq[i])
            }
        ]
    }

    function createContents(patientId: String){
        contents = [
            createGraphsWindow(patientId),
            createTextWindowContents(patientId)
        ];
        setVisibility(0);
    }

    function getNextPatientId(userName: String): String {
        var PID: String = null;
        if (patientIdList.isEmpty()) {
            def surveyRS = DBConnection.query(connection, "SELECT patientId FROM {surveyTable} "
            "WHERE userName = '{userName}' AND isFinished = 0");
            if (surveyRS.first() == false) {
                PID = null;
                Alert.inform(finishedMessage);
                DBConnection.updateQuery(connection, "UPDATE {inDBName}.account SET completed = 1 WHERE "
                "userName = '{userName}' AND completed != 1");
            }
            else {
                try {
                    surveyRS.previous();
                } catch(ex : SQLException) {
                    ex.printStackTrace();
                }

                while (surveyRS.next())  {
                    insert surveyRS.getString('patientId') into patientIdList;
                }
                PID = patientIdList[0];
            }
        }
        else {
            PID = patientIdList[0];
        }
        return PID;
    }

    function createHeadLine(patientId: String): Text {
        def demographicsRS = DBConnection.query(connection, "SELECT text FROM {inDBName}.demographics WHERE patientId = '{patientId}'");
        if (demographicsRS.next()) {
            return Text {
                content: demographicsRS.getString('text');
                font : font2
                y: font2.size
            }
        }
        else return null;
    }

    function setVisibility(tabIdx: Integer) {
        for (i in [0..sizeof contents - 1])
            if (i!= tabIdx) contents[i].visible = false;
        contents[tabIdx].visible = true;
//        System.gc();
    }

    public override function create(): Node {
        var PID: String;
        PID = getNextPatientId(userName);

        if (PID == null) return null
        else patientId = PID;

//        graphsWindow = createGraphsWindow (patientId);
//        textWindowContents = createTextWindowContents(patientId);
        createContents(patientId);


        def headerRect = Rectangle {	// skyblue box on the top (patient info)
            width: bind screenWidth
            height: bind headerRectHeight
            fill: Color.LIGHTBLUE
            stroke: Color.LIGHTGRAY
            strokeWidth: 3
        }

        def bgRect = Rectangle {    // red outter box
            translateY: headerRectHeight
            width: screenWidth
            height: screenHeight - headerRectHeight
            fill: Color.WHITE
            stroke: Color.BROWN
            strokeWidth: 4
        }

        var graphsTab: Button = Button {    // 1st tab
            text: "Graphs View"
            font: tabFont2
            layoutInfo: LayoutInfo {
                width: tabWidth
            }
            action: function () {
//                setVisibility(graphsWindow);
                setVisibility(0)
            }
        }

        def tabsView = HBox {	// generating tabs on the top
            translateY: tabsYOffset
            content: [graphsTab, createTextModeTabs()]	// has graphsTab, which is on the right above, and output of createTextModeTabs()
            spacing: -tabSpacing
        }

        def nextPatientButton = Button {
            def nextPatientButtonWidth = 120;
            text: "Next Patient"
            translateX: bind screenWidth - nextPatientButtonWidth
            layoutInfo: LayoutInfo {
                    width: nextPatientButtonWidth
                }
            action: function() {
                delete patientIdList[0];
                PID = getNextPatientId(userName);
                if (PID != null) {
                    patientId = PID;
                    createContents(patientId);
//                    System.gc();
                }
            }
        }

        var headLine: Text = bind createHeadLine(patientId);
        

        return Group {
            content: bind [ headerRect, headLine, nextPatientButton, tabsView, bgRect, contents ]
        }

    }
}
